package cc.opcol.iot.server.sdk;

import cc.opcol.iot.server.domain.JsEventHandle;
import cc.opcol.iot.server.parser.JsSessionEventHandle;
import cc.opcol.iot.server.repo.MongoEventHandleRepository;
import cc.opcol.iot.server.server.SessionManager;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Component
public class JSInterface {


    @Autowired
    JsSessionEventHandle jsSessionEventHandle;

    @Autowired
    ScriptEngineHelper scriptEngineHelper;


    ApplicationContext applicationContext;

    @Autowired
    MongoEventHandleRepository mongoEventHandleRepository;

    @Value("${spring.data.mongodb.host}")
    private String mongoHost="";

    @Autowired
    JSRepositoryAgent jsRepositoryAgent;


    @PostConstruct
    public void loadAll(){
        jsRepositoryAgent.setApplicationContext(applicationContext);
        jsSessionEventHandle.setScriptEngineHelper(scriptEngineHelper);
        List<JsEventHandle> jsEventHandles=mongoEventHandleRepository.queryAllByIdDesc();
        for(JsEventHandle jsEventHandle : jsEventHandles){
            if(jsEventHandle.getEnable()==1) {
                jsSessionEventHandle.addJsEvent(jsEventHandle);
            }
        }
        SessionManager.addSessionEventHandle("",jsSessionEventHandle);
    }

    public void loadAllEventScript(){
        jsSessionEventHandle.cleanJsEvent();
        List<JsEventHandle> jsEventHandles=mongoEventHandleRepository.queryAllByIdDesc();
        for(JsEventHandle jsEventHandle : jsEventHandles){
            if(jsEventHandle.getEnable()==1) {
                jsSessionEventHandle.addJsEvent(jsEventHandle);
            }
        }
        jsSessionEventHandle.checkTimer();
    }


    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public void setApplicationContext(ApplicationContext applicationContext) {
        jsRepositoryAgent.setApplicationContext(applicationContext);
        this.applicationContext = applicationContext;
    }
}
